//
//  WBUserAccount.swift
//  WeiboSwift
//
//  Created by hfwd on 2017/5/25.
//  Copyright © 2017年 hfwd. All rights reserved.
//

import UIKit

private let accountFilePath : String = "/userAccount.json"
///用户账户信息
class WBUserAccount: NSObject {
    
    /// 访问令牌
    var access_token: String?
    
    /// 用户代号
    var uid: String?
    
    /// 用户姓名
    var screen_name: String?
    
    /// 用户头像
    var avatar_large: String?
    
    /// 访问令牌过期秒数，单位秒
    var expires_in: TimeInterval = 0.0 {
        
        didSet {
            
            expiresDate = Date.init(timeIntervalSinceNow: expires_in)
        }
    }
    
    /// 访问令牌过期日期
    var expiresDate: Date?
    
    override init() {
        super.init()
        
        var path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        path.append(accountFilePath)
        
        guard let data = NSData(contentsOfFile: path),
        let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String : AnyObject]
            
            else {
            
            return
        }
        
        //决定用户是否登录
        yy_modelSet(with: dict ?? [:])
        
        //  token 过期了
        if expiresDate?.compare(Date()) != .orderedDescending  {
            
            print("token 过期了")
            
            //清空token信息
            access_token = nil
            
            uid = nil
            
            _ = try? FileManager.default.removeItem(atPath: path)
        }
    }
    
    override var description: String {
        
        return yy_modelDescription()
    }
    
    func saveUserAccount() {
        
        var dict = (self.yy_modelToJSONObject() as? [String: AnyObject]) ?? [:]
        
        dict.removeValue(forKey: "expires_in")
        
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: [])
            else {
            return
        }
        
        var path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        path.append(accountFilePath)
        
        (data as NSData).write(toFile: path, atomically: true)
        
        print(path)
    }
}
